import {
  RouterMount,
  createRouter,
  runtimeQuit
} from 'uni-simple-router'
import store from '@/store'

const router = createRouter({
  platform: process.env.VUE_APP_PLATFORM,
  // 使用uni-simple-router时处理app端的退出
  routerErrorEach: ({
    type,
    msg
  }) => {
    // #ifdef APP-PLUS
    if (type === 3) {
      router.$lockStatus = false
      runtimeQuit()
    }
    // #endif
  },
  routes: [...ROUTES]
})


// 白名单
const whiteList = [
  // '/', // 注意入口页必须直接写 '/'
  '/pages/login/login'
]

//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
  // 判断当前窗口是白名单，如果是则不重定向路由
  const inWhite = whiteList.findIndex((item) => item === to.fullPath) > -1
  const token = uni.getStorageSync('token')

  // console.log('----router beforeEach-----', to.fullPath, inWhite)

  if (!inWhite && !token) {
    // console.log('----没有token需要跳转登录页面-----')
    next('/pages/login/login')
  } else {
    const userInfo = store.state.user.userInfo
    if (!userInfo) {
      try {
        await store.dispatch('user/getUserInfo')
      } catch (error) {
        await store.dispatch('user/logout')
      }
    }
    next()
  }
})

// 全局路由后置守卫
// router.afterEach((to, from) => {
//   console.log('路由拦截器....after')
// })

export {
  router,
  RouterMount
}
